
//  HomeViewController.m
//  DriverFramework
//
//  Created by Qianxia on 2017/1/4.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "HomeViewController.h"
#import "ListenToSingleModeViewController.h"
#import "GrabSinglePopViewController.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <QXYueYueModels/QXYueYueModels-umbrella.h>
#import <DriverLoginManager/DriverLoginManager-umbrella.h>
#import "DLLApiManager.h"
#import <MJRefresh/MJRefresh.h>
#import "HomeMessageInformationListOfCenterModel.h"
#import "HomeMessageTableViewCell.h"
#import <QXSocketManager/QXSocketManager.h>
#import "HeaderMacro.h"
#import "GrabSinglePopViewController.h"
#import "orderDetailsViewController.h"
#import "ongoingOrdersViewController.h"
#import "endTheTripViewController.h"
#import "HomePageWillBeginOrderCell.h"
#import <QXYangqilingDriverOfMy/QXYangqilingDriverOfMy-umbrella.h>
#import "IflyMSCManager.h"
#import "iflyMSC/iflyMSC.h"
#import "ConfigureKeyHeader.h"
#import "carEndTheTripViewController.h"
#import "LocationManager.h"
#import "UserLocationModel.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <QXDataManager/QXDataManager.h>
#import "paymentOrderDetailsViewController.h"
#import "NotificationNameManager.h"
#import "HomePageAppointOrderWarningModel.h"
#import "DetailsOfChargesVC.h"
#import "OrdersViewController.h"
#import "BaseViewController.h"
#import "RootViewController.h"
#import "SendLocationModel.h"
#import "SendLocationManager.h"
#define TimeOfRotationAnimation 2.0 // 旋转动画旋转一圈的时间

enum OrderJumpState // 订单跳转状态
{
    OrderJumpState_NotBegin, ///< 行程未开始
    OrderJumpState_GrabOrder,     ///< 跳转到可抢订单页面
    OrderJumpState_Driving,   ///< 去接乘客->到达目的地
    OrderJumpState_Settlement, ///< 结算
    OrderJumpState_LongtimeNotPay /// 长时间未支付
};
typedef enum OrderJumpState OrderJumpState;

@interface HomeViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate , SendLocationManagerDelegate>
/// 背景
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;

/**
 出车动画imageView
 */
@property (weak, nonatomic) IBOutlet UIImageView *outOfDriverImageView;


/**
 是否已经出车
 默认没有出车 NO
 */
@property(nonatomic , assign) BOOL isOutOfDriver;

/**
 收车按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *closeCarButton;



/// 提示语顶部约束，显示为0，隐藏为-30，默认为-30
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *promptViewTop;
/// 提示语图片
@property (weak, nonatomic) IBOutlet UIImageView *promptImageView;
/// 提示语内容
@property (weak, nonatomic) IBOutlet UILabel *promptLabel;

/// 首页消息列表
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/// tableView header背景
@property (weak, nonatomic) IBOutlet UIImageView *headerBackgroundImageView;
/// 出车时间
@property (weak, nonatomic) IBOutlet UILabel *drivingTimeLabel;
/// 完成订单数
@property (weak, nonatomic) IBOutlet UILabel *completeOrderNumberLabel;
/// 收入流水
@property (weak, nonatomic) IBOutlet UILabel *incomeLabel;


/**
 消息中心数据源
 */
@property(nonatomic , strong) NSMutableArray *informationListOfCenterDataSource;

/**
 消息中心获取的列表信息的当前页数
 */
@property(nonatomic , assign) NSInteger nowPageOfInformationListOfCenter;


/**
 出车按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *driverActionButton;


/**
 是否正在处理收到的订单
 */
@property(nonatomic , assign) BOOL isDealingReceivedOrder;


/**
 展示网络状态的背景视图的高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *showNetStatusBackViewHeight;

/**
 展示网络状态的背景视图
 */
@property (weak, nonatomic) IBOutlet UIView *showNetStatusBackView;





/**
 将要开始订单数据源
 */
@property(nonatomic , strong) NSMutableArray *willBeginOrderDataSource;




/**
 是否正在检查出车状态,如果正在检查出车状态屏蔽掉其他的检查请求
 */
@property(nonatomic , assign) BOOL isViewDriverStatus;

@property(nonatomic , assign) BOOL isEnterBackGround; // 是否进入后台,默认为NO


/// 推送订单的类型:推送订单(抢到) , 收到派单,收到改派的订单
@property(nonatomic , assign) TypeOfPushOrder typeOfPushOrder;


/**
 是否抢到即时单
 */
@property(nonatomic , assign) BOOL isGrabRealTime;

@property(nonatomic , copy) NSString *presentUuid;

@end

@implementation HomeViewController
- (NSMutableArray *)informationListOfCenterDataSource {
    
    if (!_informationListOfCenterDataSource) {
        self.informationListOfCenterDataSource = [NSMutableArray array];
    }
    return _informationListOfCenterDataSource;
}

- (NSMutableArray *)willBeginOrderDataSource {
    if (!_willBeginOrderDataSource) {
        self.willBeginOrderDataSource = [NSMutableArray array];
    }
    return _willBeginOrderDataSource;
}

+ (instancetype)homeViewInstance {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Root" bundle:nil];
    
    return [storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"];
}

#pragma mark - 页面已经出现
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self initializationData];
    
    // 加载图片和设置布局
    [self setupViews];

    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf.nowPageOfInformationListOfCenter = 1;
        QXYYUserDriverModel*drvier = [QXYYUserDriverModel QXYY_unarchiveObject];
        if(drvier.token){ // 如果没有登录,那么进入登录页面
            
            [strongSelf getDriverMessageListOfCenterWithNowPage:strongSelf.nowPageOfInformationListOfCenter];
            [strongSelf getCurrentDrivingInfo];
            [strongSelf appointOrderWarning];
        }else {
            
            [strongSelf.tableView.mj_header endRefreshing];
        }
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf.nowPageOfInformationListOfCenter += 1;
        QXYYUserDriverModel*drvier = [QXYYUserDriverModel QXYY_unarchiveObject];
        if(drvier.token){ // 如果没有登录,那么进入登录页面
            
            [strongSelf getDriverMessageListOfCenterWithNowPage:self.nowPageOfInformationListOfCenter];
        }else {
            
            [strongSelf.tableView.mj_footer endRefreshing];
        }
        
    }];
    
    QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    if (driverModel) {
        
        if (self.isOutOfDriver) {
            
            [self.tableView.mj_header beginRefreshing];
        }
        
    }
    
    
    self.outOfDriverImageView.image = [QXDriverConfiguration imageWithName:@"public_pic_jiaodan"];
    self.outOfDriverImageView.hidden = YES;
    self.isOutOfDriver = NO;
    
    self.closeCarButton.layer.cornerRadius = 31.0;
    self.closeCarButton.layer.masksToBounds = YES;
    self.closeCarButton.hidden = YES;
    
    
    
    // 如果将要处于激活状态发送通知,然后请求司机上班状态
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_DriverWorkingState object:nil];
    
    [self addDriverLoginNotification];
    [self registerRequestDriverWorkingStateNotification];
    [self registerLongLinkNofitfication];
    [self configureDefaultAttributes];
    [self registerIsGrabOrderNotification];
    [self registerNetStatusNotification];
    
    [self registerAppEnterForceGroundNotification];
    
    [self registerAppDidBecomeActivity];
    
    self.isEnterBackGround = YES;
    if (self.isOutOfDriver) {
        
        [self areThereAnyOngoingOrders];
    }
    
}

#pragma mark - 页面将要出现
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.isOutOfDriver) { // 如果出车开启出车动画,如果没有关闭出车动画
        
        [self beginOutOfDriverAnimation];
    }else {
        
        [self endOutOfDriverAnimation];
    }
    

    
    // 页面将要出现显示正在处理订单,之后拉去订单信息如果没有订单,那么为NO,如果有订单那么为YES
    self.isDealingReceivedOrder = YES;
    
    
    // 查看是否有进行中的订单
    QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    if (driverModel.token) {
        
        if (self.isOutOfDriver) { // 页面将要出现判断是否已经出车,如果已经出车,那么获取时候有正在进行中的订单
            
            [self areThereAnyOngoingOrders]; // 页面出现就获取一次订单状态,查看是否有正在进行的订单,如果有进入订单详情
            [self.tableView.mj_header beginRefreshing];
        }else {
            
            [self getDriverWorkingState]; // 如果没有出车(app,死掉了,app进入后台了),获取出车状态
        }
        
    }else {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:DriverLoginOutSucessNotification object:nil];
    }

}


/**
 页面已经消失
 */
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [MBProgressHUD hiddenAllHUDForView:self.view animated:NO];
    
    self.isDealingReceivedOrder = YES;
    
}

#pragma mark - 配置默认属性
- (void)configureDefaultAttributes {

    self.driverActionButton.layer.cornerRadius = 45.0;
    self.driverActionButton.layer.masksToBounds = YES;
    
    
    
    
    QXYYUserDriverModel*drvierModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    if(drvierModel.token){ // 如果没有登录,那么进入登录页面
    // 初始化获取一次司机当天出车考核信息
        [self getCurrentDrivingInfo];
    }
    

    
    [SendLocationManager shareManager].delegate = self;
}




#pragma mark - 司机登录登出通知
- (void)addDriverLoginNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(driverLoginSuccess:) name:DriverLoginSucessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(driverLoginout:) name:DriverLoginOutSucessNotification object:nil];
}

// 登录成功
- (void)driverLoginSuccess:(NSNotification *)notification {
    
    //判断是否之前有登录 链接长连接
    QXYYUserDriverModel*driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    
    if (driverModel.token) {
        
        [[QXSocketManager manager] close];
//        [[QXSocketManager manager] loginWithUserId:driverModel.uuid token:driverModel.token isDriver:YES]; // 如果出车成功,那么开启长链接
        
        [self.willBeginOrderDataSource removeAllObjects];
        [self.tableView reloadData];

        if (self.isOutOfDriver) {
            
            [self.tableView.mj_header beginRefreshing];
        }
        
    }
    
    [self registerLongLinkNofitfication];
    
}

// 退出登录
- (void)driverLoginout:(NSNotification *)notification {
    
    [self.informationListOfCenterDataSource removeAllObjects];
    dispatch_async(dispatch_get_main_queue(), ^{

        [[QXSocketManager manager] close];
//        [QXYYUserDriverModel QXYY_archiveObject:nil];
        self.isOutOfDriver = NO;
        [self.tableView reloadData];
        
        
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        /// 这里清空这个账号的出车信息
        [self notGetHomePageDrivingInfo];
        self.isOutOfDriver = NO;
        [self endOutOfDriverAnimation];
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_UploadLocationTimer_Close object:nil];
    });
}

#pragma mark - 注册App处于激活状态的通知
- (void)registerAppDidBecomeActivity {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActivityAction:) name:NotificationName_AppEnterForceGround object:nil];
}

- (void)appDidBecomeActivityAction:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:NotificationName_AppBecomeActivity]) {
        
    }
}

#pragma mark - 注册app进入前端的通知
- (void)registerAppEnterForceGroundNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForceGroundAction:) name:NotificationName_AppEnterForceGround object:nil];
}

- (void)appEnterForceGroundAction:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:NotificationName_AppEnterForceGround]) {
        
        
    }
}


#pragma mark - 注册司机工作状态的通知
- (void)registerRequestDriverWorkingStateNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDriverWorkingState:) name:Notification_DriverWorkingState object:nil]; // app 将要激活的时候获取司机出车状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeDriverOutAnimation:) name:Notification_DirverDidEnterBackGround object:nil]; // app 将要进入后台后移除出车动画
}

// 获取司机上班状态
- (void)getDriverWorkingState:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:Notification_DriverWorkingState]) {
        
        QXYYUserDriverModel*drvier = [QXYYUserDriverModel QXYY_unarchiveObject];
        if(drvier.token){ // 如果登录
            
            if (!self.isOutOfDriver) {
                
                [self getDriverWorkingState];
            }
        }
    }
}

- (void)removeDriverOutAnimation:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:Notification_DirverDidEnterBackGround]) {
        
        self.isEnterBackGround = YES;
        self.isOutOfDriver = NO;
        self.isViewDriverStatus = NO;
        [self endOutOfDriverAnimation];
        
    }
}



#pragma mark - 注册通知是否抢到通知
- (void)registerIsGrabOrderNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(grabRealTimeOrderAction:) name:NotificationName_GrabRealTimeOrder object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(grabAppointmentOrderAction:) name:NotificationName_GrabAppointTimeOrder object:nil];
}

/**
 抢到实时单
 */
- (void)grabRealTimeOrderAction:(NSNotification *)aNotification {
    
    self.isGrabRealTime = YES;
}

/**
 抢到预约单
 */
- (void)grabAppointmentOrderAction:(NSNotification *)aNotification {
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        QXYYOrderDetailModel *orderDetailModel = aNotification.object[@"QXYYOrderDetailModel"];
        QXYYUserPassengerModel *userPassengerModel = aNotification.object[@"QXYYUserPassengerModel"];
        
        [self pushIntoOrdersDetailsViewControllerViewAppointOrderWithOrdersDetailsModel:orderDetailModel UserPassengerModel:userPassengerModel];
    });
}

/// 进入订单详情查看预约单
- (void)pushIntoOrdersDetailsViewControllerViewAppointOrderWithOrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    orderDetailsViewController *orderDetailVC = [orderDetailsViewController shareSelf];
    orderDetailVC.title = @"订单详情";
    orderDetailVC.ordersDetailsModel = ordersDetailsModel;
    orderDetailVC.userPassengerModel = userPassengerModel;
    orderDetailVC.entranceType = 1;
    orderDetailVC.isPoPToRootVC = YES;
    
    [self.navigationController pushViewController:orderDetailVC animated:YES];
    
}

#pragma mark - 注册长链接通知
- (void)registerLongLinkNofitfication {

    [self removeLonglink];

    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LonglinkCode_Order_Push] notificationName:LongLinkNoftificationName_OrderPush];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_OrderPush object:nil]; // 可抢订单
    
    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Delivery] notificationName:LongLinkNoftificationName_OrderDelivery];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_OrderDelivery object:nil]; // 订单派送
    
    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Passenger_Cancel] notificationName:LongLinkNoftificationName_PassengerCancelOrder];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_PassengerCancelOrder object:nil]; // 乘客取消订单
    
    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Passenger_PayOff] notificationName:LongLinkNoftificationName_PassengerPayOff];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_PassengerPayOff object:nil]; // 乘客付清
    
    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Changed] notificationName:LongLinkNoftificationName_OrderChanged];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_OrderChanged object:nil]; // 订单被改派
    
    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_ReceivedChangedOrder] notificationName:LongLinkNoftificationName_ReceivedChangedOrder];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_ReceivedChangedOrder object:nil]; // 收到被改派订单
    
    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Passenger_TravelAskFor] notificationName:LongLinkNoftificationName_PassengerAskForTravel];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_PassengerAskForTravel object:nil]; // 乘客申请行程
    
    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_MatchingSuccess] notificationName:LongLinkNoftificationName_OrderMatchingSuccess];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_OrderMatchingSuccess object:nil]; // 订单匹配成功(推送给司机)
    
    [[QXSocketManager manager] registerType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_BackgroundShutdown] notificationName:LongLinkNoftificationName_OrderBackShutdown];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderInfo:) name:LongLinkNoftificationName_OrderBackShutdown object:nil]; // 后台关闭订单(推送给司机)
}

- (void)removeLonglink {
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LonglinkCode_Order_Push] notificationName:LongLinkNoftificationName_OrderPush];
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Delivery] notificationName:LongLinkNoftificationName_OrderDelivery];
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Passenger_Cancel] notificationName:LongLinkNoftificationName_PassengerCancelOrder];
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Passenger_PayOff] notificationName:LongLinkNoftificationName_PassengerPayOff];
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Changed] notificationName:LongLinkNoftificationName_OrderChanged];
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_ReceivedChangedOrder] notificationName:LongLinkNoftificationName_OrderChanged];
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_Passenger_TravelAskFor] notificationName:LongLinkNoftificationName_PassengerAskForTravel];
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_MatchingSuccess] notificationName:LongLinkNoftificationName_OrderMatchingSuccess];
    
    [[QXSocketManager manager] removeNotificationType:[NSString stringWithFormat:@"%d" , LongLinkCode_Order_BackgroundShutdown] notificationName:LongLinkNoftificationName_OrderBackShutdown];
}


#pragma mark - 获取推送订单信息

- (void)getOrderInfo:(NSNotification *)aNotification {
    
    if (!self.isOutOfDriver) {
        
        return;
    }
    
    NSLog(@"anotitticandndndndn");
    NSMutableDictionary *dic = [aNotification.object mutableCopy];
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@"PUSH_RESPONSE" forKey:@"type"];
    [[QXSocketManager manager] send:dic];  // 告知服务器我收到消息了
    
    
    if ([aNotification.name isEqualToString:LongLinkNoftificationName_OrderPush] || [aNotification.name isEqualToString:LongLinkNoftificationName_OrderDelivery] || [aNotification.name isEqualToString:LongLinkNoftificationName_ReceivedChangedOrder]) { // 收到订单推送,抢单
        
        
        if (self.presentUuid != nil) {
            
            return;
        }
        if (!self.isDealingReceivedOrder) { // 如果没有处于正在处理订单的状态,可以继续接单
            
            
            NSString *orderUuid = [NSString stringWithFormat:@"%@" , aNotification.object[@"data"][@"orderUuid"]];
            self.presentUuid = orderUuid;
            if (orderUuid.length <= 0 || [orderUuid isKindOfClass:NULL]) { // 如果订单id不存在不在执行
                
                return;
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_PausePlayback object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_CompositeCancel object:nil];
            NSString *speechText = aNotification.object[@"data"][@"report"];
            IflyMSCManager *iflyMSCManager = [IflyMSCManager startSyntheticSpeechWithText:speechText];
            [iflyMSCManager.iFlySpeechSynthesizer setParameter:[NSString stringWithFormat:@"80"] forKey:[IFlySpeechConstant SPEED]];
            
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setValue:orderUuid forKey:@"orderUuid"];
            
            if ([aNotification.name isEqualToString:LongLinkNoftificationName_OrderPush]) { // 收到可抢订单
                
                self.typeOfPushOrder = TypeOfPushOrder_Push;
            }else if ([aNotification.name isEqualToString:LongLinkNoftificationName_OrderDelivery]) { // 收到指派订单
                
                self.typeOfPushOrder = TypeOfPushOrder_Delivery;
            }else if ([aNotification.name isEqualToString:LongLinkNoftificationName_ReceivedChangedOrder]) { // 收到被改派的订单
                
                self.typeOfPushOrder = TypeOfPushOrder_ReceivedChangedOrder;
            }else { // 其他视为可抢订单
                
                self.typeOfPushOrder = TypeOfPushOrder_Push;
            }
            
            [self getOrderDetailInfoWithParameters:parameters OrderJumpState:OrderJumpState_GrabOrder]; // 进入抢单页面
        }
    };
    
    
    
    if ([aNotification.name isEqualToString:NotificationName_LongLink_PassengerCancelOrder] || [aNotification.name isEqualToString:NotificationName_LongLink_OrderChanged] || [aNotification.name isEqualToString:NotificationName_LongLink_BackShutDownOrder]) { // 乘客取消订单

        BOOL isCancelOrder = [[QXDataManager getValueForKey:[NSString stringWithFormat:@"%@_OrderCancel" , aNotification.object[@"data"][@"orderUuid"]]] boolValue];
        
        if (!isCancelOrder) {
        
            
            IflyMSCManager *iflyMSCManager = [IflyMSCManager startSyntheticSpeechWithText:aNotification.object[@"data"][@"content"]];
            [iflyMSCManager.iFlySpeechSynthesizer setParameter:[NSString stringWithFormat:@"80"] forKey:[IFlySpeechConstant SPEED]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView.mj_header beginRefreshing];
            });
            
        }
        

        [QXDataManager saveValue:[NSString stringWithFormat:@"1"] forKey:[NSString stringWithFormat:@"%@_OrderCancel" , aNotification.object[@"data"][@"orderUuid"]]];
    }
    
    if ([aNotification.name isEqualToString:LongLinkNoftificationName_PassengerPayOff]) { // 如果乘客支付完成
        
        // 获取司机信息
        QXYYUserDriverModel*driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
        if (driverModel.uuid) {
            
            IflyMSCManager *iflyMSCManager = [IflyMSCManager startSyntheticSpeechWithText:aNotification.object[@"data"][@"content"]];
            [iflyMSCManager.iFlySpeechSynthesizer setParameter:[NSString stringWithFormat:@"80"] forKey:[IFlySpeechConstant SPEED]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView.mj_header beginRefreshing];
            });
            [self getCurrentDrivingInfo];
        }
    }
}




/**
 模态出可抢订单的页面
 测试使用
 */
- (void)presentGrabSingleVCWithCarPoolOrderDetailModel:(CarPoolOrderDetailModel *)carPoolOrderDetailModel {
    
    GrabSinglePopViewController *grabSinglePopViewController = [GrabSinglePopViewController shareSelf];
    grabSinglePopViewController.typeOfPushOrder = self.typeOfPushOrder;
    grabSinglePopViewController.carPoolOrderDetailModel = carPoolOrderDetailModel;
    
    [self presentViewController:grabSinglePopViewController animated:YES completion:^{
        
    }];
    self.presentUuid = nil;
}





#pragma mark - 注册网络状态的通知
- (void)registerNetStatusNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(monitorNetStatus:) name:NotificationName_ReachabilityStatusNotReachable object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(monitorNetStatus:) name:NotificationName_ReachabilityStatusReachableViaWWAN object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(monitorNetStatus:) name:NotificationName_ReachabilityStatusReachableViaWiFi object:nil];
}

- (void)monitorNetStatus:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:NotificationName_ReachabilityStatusNotReachable]) {
        
        [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionCurveEaseOut) animations:^{
            self.showNetStatusBackView.hidden = NO;
            self.showNetStatusBackViewHeight.constant = 30.0;
            [self.view layoutIfNeeded];
        } completion:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (self.isOutOfDriver) { // 出车状态如果没有网络
                
                [self endOutOfDriverAnimation]; // 查询出车状态
                [self.driverActionButton setTitle:@"连接中" forState:(UIControlStateNormal)];
            }
            
        });
    }
    
    if ([aNotification.name isEqualToString:NotificationName_ReachabilityStatusReachableViaWWAN]) {
        
        [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionCurveEaseOut) animations:^{
            self.showNetStatusBackView.hidden = YES;
            self.showNetStatusBackViewHeight.constant = 0.0;
            [self.view layoutIfNeeded];
        } completion:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
            if (driverModel.token) {
                if (!self.isOutOfDriver) { // 如果处于出车状态,不在查询
                    
                    [self getDriverWorkingState]; // 查询出车状态
                }
            }
        });
    }
    
    if ([aNotification.name isEqualToString:NotificationName_ReachabilityStatusReachableViaWiFi]) {
        
        [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionCurveEaseOut) animations:^{
            self.showNetStatusBackView.hidden = YES;
            self.showNetStatusBackViewHeight.constant = 0.0;
            [self.view layoutIfNeeded];
        } completion:nil];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
            if (driverModel.token) {
                
                if (!self.isOutOfDriver) { // 如果处于出车状态,不在查询
                    
                    [self getDriverWorkingState]; // 查询出车状态
                }
            }
        });
    }
    
}





#pragma mark - 内容警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 初始化数据

/**
 *  初始化数据
 */
- (void)initializationData {
    
    
    QXYYUserDriverModel*driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    if (!driverModel) { // 如果重新启动没有登录那么进入登录页面
        
        [self.navigationController pushViewController:[LoginManageServices getDriverLoginViewControllerWithDriverType:[[QXDataManager getValueForKey:QXDriverTypeKey] integerValue]] animated:YES];
    }
    
    
    
}

/**
 *  设置布局
 */
- (void)setupViews {
    
    self.tableView.estimatedRowHeight = 100;
    
    self.backgroundImageView.image = [QXDriverConfiguration imageWithName:@"bg"];
    self.promptImageView.image = [QXDriverConfiguration imageWithName:@"public_nowifi"];
    self.headerBackgroundImageView.image = [QXDriverConfiguration imageWithName:@"public_bg"];
    
}





#pragma mark - Action
#pragma mark -模式
- (IBAction)modeAction:(id)sender {
    
    ListenToSingleModeViewController *listenToSingleModeViewController = [ListenToSingleModeViewController returnListenToSingleModeViewController];
    [listenToSingleModeViewController clearCache];
    [listenToSingleModeViewController presentViewAnimated:YES];
    IflyMSCManager *iflyMSCManager = [IflyMSCManager startSyntheticSpeechWithText:@"听单设置"];
    [iflyMSCManager.iFlySpeechSynthesizer setParameter:[NSString stringWithFormat:@"80"] forKey:[IFlySpeechConstant SPEED]];
    
}

#pragma mark -出车Action
- (IBAction)startOrderAction:(id)sender {
    

    [[LocationManager shareManager] openLocationServiceSetting:self];
    
    if (!self.isOutOfDriver) { // 如果已经出车不在执行(出车后能在此发送收车请求)
        
        self.presentUuid = nil;
        [self beginDriverOutRequestRequest];
    }
    
}



#pragma mark - 收车Action
- (IBAction)closeCarAction:(UIButton *)sender {
    
    if (self.isOutOfDriver) { // 如果已经出车了,那么才可以收车
        
        self.presentUuid = nil;
        [self goOffWorkingRequest];
    }
}


#pragma mark - 出车收车动画处理
- (void)rotateImg:(UIImageView *)img andCount:(CGFloat)count{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.fromValue = @(0);
    rotationAnimation.toValue = [NSNumber numberWithFloat: -M_PI * 2.0 ];
    rotationAnimation.duration = count;
    rotationAnimation.repeatCount = HUGE;
    [img.layer addAnimation:rotationAnimation forKey:@"rotationAnimation%ld"];
}


/**
 开始出车动画
 */
- (void)beginOutOfDriverAnimation {
    
    self.closeCarButton.hidden = NO;
    self.outOfDriverImageView.hidden = NO;
    [self.driverActionButton setTitle:KeyWord_ReceivingOrder forState:(UIControlStateNormal)];
    [self rotateImg:self.outOfDriverImageView andCount:TimeOfRotationAnimation];
    self.isOutOfDriver = YES;
    
}


/**
 结束出车动画
 */
- (void)endOutOfDriverAnimation {
    
    self.closeCarButton.hidden = YES;
    self.isOutOfDriver = NO;
    self.outOfDriverImageView.hidden = YES;
    [self.driverActionButton setTitle:KeyWord_DriveOut forState:(UIControlStateNormal)];
    [self.outOfDriverImageView.layer removeAnimationForKey:@"rotationAnimation"];
}

#pragma mark - 进入考核统计页面
- (IBAction)pushIntoAssessmentOfStatistical:(id)sender {
    
    // 考核统计
    [self.navigationController pushViewController:[AssessmentOfStatisticalTableViewController shareInstance] animated:YES];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    switch (section) {
        case 0: {
            
            return self.willBeginOrderDataSource.count;
            break;
        }
        case 1: {
            
            return self.informationListOfCenterDataSource.count;
            break;
        }
            
        default: {
            
            return 0;
            break;
        }
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"messageCell" forIndexPath:indexPath];
    
    switch (indexPath.section) {
        case 0: {
            
            cell = [self dealHomePageWillBeginOrderCellWithTableView:tableView indexPath:indexPath];
            break;
        }
            
        case 1: {
            
            cell = [self dealHomeMessageTableViewCellWithTableView:tableView indexPath:indexPath];
            break;
        }
        default: {
            
            
            break;
        }
    }
    
    
    
    return cell;
}


/**
 展示消息的cell
 */
- (HomeMessageTableViewCell *)dealHomeMessageTableViewCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    
    
    
    HomeMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"messageCell" forIndexPath:indexPath];
    
    if (indexPath.row < self.informationListOfCenterDataSource.count) {
        
        HomeMessageInformationListOfCenterModel *model = self.informationListOfCenterDataSource[indexPath.row];
        [cell setValueWithHomeMessageInformationListOfCenterModel:model];
    }
    
    __weak typeof(self) weakSelf = self;
    cell.deleteMsgBlockAction = ^() {
        __strong typeof(self) strongSelf = weakSelf;
        NSString *uuid;
        [strongSelf deleteMessageWithUuid:uuid indexPath:indexPath];
    };
    
    return cell;
}

- (HomePageWillBeginOrderCell *)dealHomePageWillBeginOrderCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    
    HomePageWillBeginOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomePageWillBeginOrderCellID" forIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        
        if (indexPath.row < self.willBeginOrderDataSource.count) {
            
            HomePageAppointOrderWarningModel *model = self.willBeginOrderDataSource[indexPath.row];
            
            [cell setValueWithHomePageAppointOrderWarningModel:model];
        }
    }
    
    
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0: {
            
            [self viewWillBeginOrderWithIndexPath:indexPath];
            break;
        }
        case 1: {
            
            break;
        }
        default:
            break;
    }
    
}



#pragma mark - 首页消息列表如果有将要开始的订单
- (void)viewWillBeginOrderWithIndexPath:(NSIndexPath *)indexPath {
    
    if (self.willBeginOrderDataSource.count > indexPath.row) {
        
        HomePageAppointOrderWarningModel *model = self.willBeginOrderDataSource[indexPath.row];
        NSString *orderUuid = model.orderUuid;
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setValue:orderUuid forKey:@"orderUuid"];
        [self getOrderDetailInfoWithParameters:parameters OrderJumpState:OrderJumpState_NotBegin]; // 进入页面
    }
    
}



#pragma mark - 获取首页消息列表信息请求
/**
 获取消息中心列表信息
 */
- (void)getDriverMessageListOfCenterWithNowPage:(NSInteger)nowPage {

    NSMutableDictionary *parametes = [NSMutableDictionary dictionary];
    [parametes setValue:@(nowPage) forKey:@"nowPage"];
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager getDriverHomePageMessageWithParameters:parametes success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        if (nowPage == 1) {
            
            [strongSelf.informationListOfCenterDataSource removeAllObjects];
            
        }
        
        if (NetWork_Success) {
            
            NSArray *dataArray = data[@"data"];
            if ([dataArray isKindOfClass:[NSArray class]]) {
                
                if (dataArray.count > 0) {
                    
                    for (NSDictionary *dataDictionary in dataArray) {
                        
                        HomeMessageInformationListOfCenterModel *model = [HomeMessageInformationListOfCenterModel new];
                        [model setValuesForKeysWithDictionary:dataDictionary];
                        [strongSelf.informationListOfCenterDataSource addObject:model];
                    }
                }else {
                    
                }
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
            [strongSelf.tableView.mj_footer endRefreshing];
            [strongSelf.tableView reloadData];
        });
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *hud = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            hud.userInteractionEnabled = NO;
            [strongSelf.tableView.mj_header endRefreshing];
            [strongSelf.tableView.mj_footer endRefreshing];
        });
    }];
}

#pragma mark - 删除消息
/// 删除消息
- (void)deleteMessageWithUuid:(NSString *)uuid indexPath:(NSIndexPath *)indexPath {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    });
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@"uuid" forKey:@"uuids"];
    __weak typeof(self) weakSelf = self;
    [DLLApiManager deleteHomePageMessageWithParameters:parameters success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
           
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
            
            if (NetWork_Success) {
                
//                self.informationListOfCenterDataSource 
                
            }else {
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            }
            
        });
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        });
    }];
}

#pragma mark - 获取司机上下班状态

/**
 获取司机上下班状态
 */
- (void)getDriverWorkingState {
    
    [[LocationManager shareManager] openLocationServiceSetting:self];
   
    self.presentUuid = nil;
    if (self.isViewDriverStatus) { // 如果正在获取出车状态,那么不在执行
        
        return;
    }
    self.isViewDriverStatus = YES; // 正在获取出车状态请求
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = NO;
    });

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:[NSString stringWithFormat:@"%@" , [QXDataManager getValueForKey:QXDriverTypeKey]] forKey:@"type"];
    __weak typeof(self) weakSelf = self;
    [DLLApiManager getDriverWorkingStateWithParameters:parameters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
        });

        if (NetWork_Success) {
            
            // 获取司机信息
            QXYYUserDriverModel*driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
            
            if ([data[@"data"] integerValue] == 2) { // 正在上班
                
                strongSelf.isOutOfDriver = YES;
                strongSelf.isViewDriverStatus = YES; // 如果查询到正在出车,继续查询是否有进行中的订单,这里继续加
                dispatch_async(dispatch_get_main_queue(), ^{ // 如果正在上班那么开启长链接
                    
                    if(driverModel.token){
                        [[QXSocketManager manager] close];
                        [[QXSocketManager manager] loginWithUserId:driverModel.uuid token:driverModel.token isDriver:YES];
                        
                        // 如果出车了那么开启定时器
                        [[SendLocationManager shareManager] startTimer];
                        
                        [strongSelf areThereAnyOngoingOrders]; // 如果出车了查看是否有正在进行中的订单
                        [strongSelf getCurrentDrivingInfo]; // 如果正在上班刷新司机出车信息
                    }
                    [strongSelf beginOutOfDriverAnimation];
                });
                
            }else {
                
                strongSelf.isOutOfDriver = NO;
                strongSelf.isViewDriverStatus = NO;
                strongSelf.isDealingReceivedOrder = NO;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
//                    [[QXSocketManager manager] loginWithUserId:@"" token:@"" isDriver:YES]; // 如果没有出车,那么关闭长链接
                    [[QXSocketManager manager] close];
                    [strongSelf endOutOfDriverAnimation];
                });
                
            }
            
        }else {
            
            strongSelf.isOutOfDriver = NO;
            strongSelf.isViewDriverStatus = NO;
            strongSelf.isDealingReceivedOrder = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                
//                [[QXSocketManager manager] loginWithUserId:@"" token:@"" isDriver:YES]; // 如果没有出车,那么关闭长链接
                [[QXSocketManager manager] close];
                [strongSelf endOutOfDriverAnimation];
            });
        }
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            strongSelf.isViewDriverStatus = NO;
//            [[QXSocketManager manager] loginWithUserId:@"" token:@"" isDriver:YES]; // 如果网络信息获取失败关闭长链接
            [[QXSocketManager manager] close];
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            strongSelf.isOutOfDriver = NO;
            [strongSelf endOutOfDriverAnimation];
        });
    }];
}


/**
 司机只要出车就发送位置信息到服务端
 */
-(void)sendDriverLocation {
    
//    return;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    // 纬度
    double lat = [LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude;
    // 精度
    double lng = [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude;
    
    if (lat == 0 || lng == 0 || [LocationManager shareManager].userLocationModel == nil) { // 还未定位成功
        
        return;
    }
    
    // 角度
    NSString *angle = [NSString stringWithFormat:@"%f" , [LocationManager shareManager].userLocationModel.userLocation.course];
    
    [parameters setValue:@(0) forKey:@"distance"];
    [parameters setValue:@(lat) forKey:@"lat"];
    [parameters setValue:@(lng) forKey:@"lng"];
    [parameters setValue:angle forKey:@"angle"];
    [parameters setValue:@"UPLOAD_LOCATION" forKey:@"type"];
    [parameters setValue:@([[QXDataManager getValueForKey:QXDriverTypeKey] integerValue]) forKey:@"driverType"];
    [parameters setValue:[QXDataManager getValueForKey:QXAppId] forKey:@"appid"];
    QXYYUserDriverModel*driver = [QXYYUserDriverModel QXYY_unarchiveObject];
    [parameters setValue:driver.uuid forKey:@"driverUuid"];
    [parameters setValue:@"DRIVER" forKey:@"from"];
    [parameters setValue:driver.uuid forKey:@"clientUuid"];
    [parameters setValue:driver.token forKey:@"token"];
    [parameters setValue:@(0) forKey:@"mileage"];
    
    // 三级等保 的参数
    // 行政编码
    [parameters setValue:[LocationManager shareManager].userLocationModel.adcode forKey:@"driverRegionCode"];
    // 海拔高度
    [parameters setValue:@([LocationManager shareManager].userLocationModel.altitude) forKey:@"elevation"];
    // 营运状态
    [parameters setValue:@(CarryPassengerStatusDeadhead) forKey:@"bizStatus"];
    // 瞬时速度
    [parameters setValue:@([LocationManager shareManager].userLocationModel.speed) forKey:@"speed"];
    // 订单id
    [parameters setValue:@"" forKey:@"orderUuid"];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [[QXSocketManager manager] send:parameters];
    });
}

#pragma mark - 开始出车请求
/**
 开始出车请求
 */
- (void)beginDriverOutRequestRequest {
    
    // 纬度
    double lat = [LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude;
    // 精度
    double lng = [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude;
    
    if (lat == 0 || lng == 0 || [LocationManager shareManager].userLocationModel == nil) { // 还未定位成功
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:NO];

                
            MBProgressHUD *mb1 = [MBProgressHUD showWithText:@"定位中..." onView:self.view hiddenDuration:2.0];
            mb1.userInteractionEnabled = NO;
            
            
        });
        return;
    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@(lat) forKey:@"onWorkLat"];
    [parameters setValue:@(lng) forKey:@"onWorkLng"];
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverStartWorkingWithParameters:parameters success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        });
        
        if (NetWork_Success) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                strongSelf.isOutOfDriver = YES;
                // 如果出车了那么开启定时器
                [[SendLocationManager shareManager] startTimer];
                [strongSelf areThereAnyOngoingOrders]; // 如果出车成功查看是否有正在进行中的订单
                // 获取司机信息
                QXYYUserDriverModel*driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
                [[QXSocketManager manager] close];
                [[QXSocketManager manager] loginWithUserId:driverModel.uuid token:driverModel.token isDriver:YES]; // 如果出车成功,那么开启长链接
                [strongSelf registerLongLinkNofitfication];
                [strongSelf beginOutOfDriverAnimation];
                
            });
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
               
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
                strongSelf.isOutOfDriver = NO;
                [strongSelf endOutOfDriverAnimation];
            });
        }
        
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
            strongSelf.isOutOfDriver = NO;
        });
        
    }];
}


#pragma mark - 查看是否有正在进行中的订单
- (void)areThereAnyOngoingOrders {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    });
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager getOrderStatusWithParameters:nil success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
        });
        
        if (NetWork_Success) {
            
            // 1: 有订单（预约单）已超过出发时间（等待接驾未出发） , 2: 有订单正在进行中，已出发，未确认金额 , 3: 有订单长时间未支付（金额确认后超过1小时未支付） , 4: 有订单（预约单）即将开始（10分钟内）
            if ([data[@"data"][@"status"] integerValue] == 2 || [data[@"data"][@"status"] integerValue] == 4 || [data[@"data"][@"status"] integerValue] == 1 || [data[@"data"][@"status"] integerValue] == 3) { // 为2的时候代表有正在进行中的订单
                
                
                if (!strongSelf.isGrabRealTime) {
                    
                    NSString *alerctTitle;
                    
                    if ([data[@"data"][@"status"] integerValue] == 1) {
                        
                        alerctTitle = @"您有订单已过出发时间,请立即处理";
                    }else if ([data[@"data"][@"status"] integerValue] == 2) {
                        
                        alerctTitle = @"您有订单仍在进行中";
                    }else if ([data[@"data"][@"status"] integerValue] == 3) {
                        
                        alerctTitle = @"您有订单已等待支付较久,可联系乘客尽快支付";
                    }else if ([data[@"data"][@"status"] integerValue] == 4) {
                        
                        alerctTitle = @"您有订单即将开始,请做好接驾准备";
                    }
                    
                    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:alerctTitle preferredStyle:(UIAlertControllerStyleAlert)];
                    
                    NSString *actionTitle;
                    
                    if ([data[@"data"][@"status"] integerValue] == 1 || [data[@"data"][@"status"] integerValue] == 4 || [data[@"data"][@"status"] integerValue] == 3) {
                        
                        actionTitle = @"查看订单";
                    }else {
                        
                        actionTitle = @"继续订单";
                    }
                    
                    if ([data[@"data"][@"status"] integerValue] == 4 || [data[@"data"][@"status"] integerValue] == 3) {
                        
                        NSString *laterOnTitle = @"稍后";
                        [alertVC addAction:[UIAlertAction actionWithTitle:laterOnTitle style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                            
                            if ([data[@"data"][@"status"] integerValue] == 3) {
                                
                                strongSelf.isEnterBackGround = NO;
                            }
                        }]];
                    }
                    
                    
                    [alertVC addAction:[UIAlertAction actionWithTitle:actionTitle style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                        
                        strongSelf.isGrabRealTime = NO;
                        strongSelf.isViewDriverStatus = YES; // 如果查询到有正在进行中的订单继续加锁
                        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
                        [parameters setValue:data[@"data"][@"orderUuid"] forKey:@"orderUuid"];
                        
                        if ([data[@"data"][@"status"] integerValue] == 1) { // 有订单（预约单）已超过出发时间（等待接驾未出发）
                            
                            [strongSelf getOrderDetailInfoWithParameters:parameters OrderJumpState:OrderJumpState_NotBegin];
                        }else if ([data[@"data"][@"status"] integerValue] == 2) { // 有订单正在进行中，已出发，未确认金额
                            
                            [strongSelf getOrderDetailInfoWithParameters:parameters OrderJumpState:OrderJumpState_Driving];
                        }else if ([data[@"data"][@"status"] integerValue] == 3) { // 有订单长时间未支付（金额确认后超过1小时未支付）
                            
                            [strongSelf getOrderDetailInfoWithParameters:parameters OrderJumpState:OrderJumpState_LongtimeNotPay];
                            
                        }else if ([data[@"data"][@"status"] integerValue] == 4) { // 有订单（预约单）即将开始（10分钟内）
                            
                            [strongSelf getOrderDetailInfoWithParameters:parameters OrderJumpState:OrderJumpState_NotBegin];
                        }
                        
                    }]];
                    id vc = strongSelf.navigationController.viewControllers.lastObject;
 
                    if (([vc isKindOfClass:[HomeViewController class]] || [vc isKindOfClass:[OrdersViewController class]] || [vc isKindOfClass:[DriverOfMyViewController class]] || [vc isKindOfClass:[BaseViewController class]] || [vc isKindOfClass:[RootViewController class]])) { // 保证只执行一次
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            if ([data[@"data"][@"status"] integerValue] == 3) {
                                
                                strongSelf.isDealingReceivedOrder = NO;
                                
                                if (strongSelf.isEnterBackGround) {
                                    
                                    [strongSelf presentViewController:alertVC animated:YES completion:nil];
                                    strongSelf.isEnterBackGround = NO;
                                    
                                }
                            }else {
                                
                                [strongSelf presentViewController:alertVC animated:YES completion:nil];
                            }
                            
                        });
                    }
                    
                }else { // 如果抢到即时订单
                    
                    strongSelf.isGrabRealTime = NO;
                    strongSelf.isViewDriverStatus = YES; // 如果没有查询到正在进行中的订单继续解锁
                    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
                    [parameters setValue:data[@"data"][@"orderUuid"] forKey:@"orderUuid"];
                    [strongSelf getOrderDetailInfoWithParameters:parameters OrderJumpState:OrderJumpState_Driving];
                }
                
                
            }else {
                
                strongSelf.isDealingReceivedOrder = NO;
                strongSelf.isViewDriverStatus = NO;
            }
            
        }else {
            
            strongSelf.isDealingReceivedOrder = NO;
            strongSelf.isViewDriverStatus = NO;
        }
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf.isDealingReceivedOrder = NO;
        strongSelf.isViewDriverStatus = NO;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
        });
    }];
}


#pragma mark - 司机下班请求
/**
 司机下班
 */
- (void)goOffWorkingRequest {
    
    // 纬度
    double lat = [LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude;
    // 精度
    double lng = [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude;
    
    if (lat == 0 || lng == 0 || [LocationManager shareManager].userLocationModel == nil) { // 还未定位成功
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];

            MBProgressHUD *mb1 = [MBProgressHUD showWithText:@"定位中..." onView:self.view hiddenDuration:2.0];
            mb1.userInteractionEnabled = NO;
            
            
        });
        return;
    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@(lat) forKey:@"offWorkLat"];
    [parameters setValue:@(lng) forKey:@"offWorkLng"];
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverGoOffWorkWithParameters:parameters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        });
        
        
        
        if (NetWork_Success) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                strongSelf.isOutOfDriver = NO;
                // 如果收车了关闭定时器
                [[SendLocationManager shareManager] stopTimer];
//                [[QXSocketManager manager] close];
//                [[QXSocketManager manager] loginWithUserId:@"" token:@"" isDriver:YES]; // 如果下班成功,那么关闭长链接
                [strongSelf endOutOfDriverAnimation]; // 如果停止出车成功那么停止出车动画
                
            });
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
                
            });
            strongSelf.isOutOfDriver = YES;
        }
        
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
            strongSelf.isOutOfDriver = YES;
        });
        
    }];
}

#pragma mark - 获取订单详情
/**
 获取订单详情
 */
- (void)getOrderDetailInfoWithParameters:(NSMutableDictionary *)parameters OrderJumpState:(OrderJumpState)orderJumpState {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    });
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager getTheOrderDetailsWithParameters:parameters success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        });
        
        if(NetWork_Success){
            
            CarPoolOrderDetailModel *carPoolOrderDetailModel = [CarPoolOrderDetailModel QXYY_objectWithKeyValues:data[@"data"]];
            QXYYOrderDetailModel * ordersDetailsModel = [QXYYOrderDetailModel QXYY_objectWithKeyValues:data[@"data"]];
            QXYYUserPassengerModel * userPassengerModel = [QXYYUserPassengerModel QXYY_objectWithKeyValues:data[@"data"][@"passenger"]];

            dispatch_async(dispatch_get_main_queue(), ^{
                if (carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_NewStroke_PassengerCancel ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_PassengersCancel_StrokeDetemination_DriverNotArrive ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_PassengersCancel_StrokeDetemination_DriverArrived ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_NewStroke_DriverCancel ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_NoFare_StrokeDetermination_PassengersCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_NoFare_GotoPickUpPassengers_PassengersCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OOrderStatusEnumCode_NoFare_WaitingForPassengers_PassengersCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_HaveFare_StrokeDetermination_PassengersCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_HaveFare_GotoPickUpPassengers_PassengersCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_HaveFare_WaitingForPassengers_PassengersCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_NoFare_StrokeDetermination_DriverCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_NoFare_GotoPickUpPassengers_DriverCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_NoFare_WaitingForPassengers_DriverCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_HaveFare_StrokeDetermination_DriverCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_HaveFare_GotoPickUpPassengers_DriverCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_HaveFare_WaitingForPassengers_DriverCancelOrder ||
                    carPoolOrderDetailModel.subStatus == OrderStatusEnumCode_OrderClosedByCustomerService) { // 如果订单被取消继续接单
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_CanReceivingOrder object:nil]; // 发送正在处理接到的订单
                    
                    [strongSelf pushIntoOrdersDetailsViewControllerWithOrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel]; // 如果行程未开始,进入订单详情
                    strongSelf.isViewDriverStatus = NO; // 可以继续检测出车状态的请求
                    
                }else { // 如果订单没有取消,进入抢单页面
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_IsDealingReceivedOrder object:nil]; // 发送正在处理接到的订单
                    
                    if (orderJumpState == OrderJumpState_GrabOrder) { // 进入抢单页面
                        
                        [strongSelf presentGrabSingleVCWithCarPoolOrderDetailModel:carPoolOrderDetailModel];  
                    }else if (orderJumpState == OrderJumpState_Settlement || orderJumpState == OrderJumpState_Driving) { // 进入结算详情页面,或者行程中详情页面
                        
                        if (ordersDetailsModel.subStatus == OrderStatusCode_PassengersArrivedDestination) { // 司机为确认费用
                            
                            strongSelf.isGrabRealTime = NO;
                            [strongSelf pushIntoendTheTripViewControllerWithOrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
                            
                            
                        }else if (ordersDetailsModel.subStatus == OrderStatusCode_DriverSetOut_GoToPickUpPassengers || ordersDetailsModel.subStatus ==OrderStatusCode_DriverArrived_WaitingForPassengers || ordersDetailsModel.subStatus == OrderStatusCode_PickedUpPasengers_StrokeStart) {
                            
                            strongSelf.isGrabRealTime = NO;
                            [strongSelf pushIntoongoingOrdersViewControllerWithOrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
                            
                        }else { // 订单状态为200,未开始的预约单
                            
                            strongSelf.isDealingReceivedOrder = NO;
                        }
                        
                        strongSelf.isViewDriverStatus = NO; // 可以继续检测出车状态的请求
                    }else if (orderJumpState == OrderJumpState_NotBegin) {
                        
                        if (ordersDetailsModel.subStatus == OrderStatusCode_DriverReceivedOrder_DetermineStroke) {
                            
                            [strongSelf pushIntoOrdersDetailsViewControllerWithOrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel]; // 如果行程未开始,进入订单详情
                            strongSelf.isViewDriverStatus = NO; // 可以继续检测出车状态的请求
                        }
                    }else if (orderJumpState == OrderJumpState_LongtimeNotPay) {
                        
                        if (ordersDetailsModel.subStatus == OrderStatusEnumCode_DriverConfirmFare_WaitingForPassengersToPay ||  ordersDetailsModel.subStatus == OrderStatusEnumCode_StrokeDetermination_PassengerCancelOrder_WaitingForPassengersToPayCancleFare|| ordersDetailsModel.subStatus == OrderStatusEnumCode_StrokeDetermination_DriverCancelOrder_WaitingForPassengersToPayCancleFare || ordersDetailsModel.subStatus == OrderStatusEnumCode_WaitingForPassengers_PassengerCancelOrder_WaitingForPassengersToPayCancleFare || ordersDetailsModel.subStatus == OrderStatusEnumCode_WaitingForPassengers_DriverCancelOrder_WaitingForPassengersToPayCancleFare) {
                            
                            [strongSelf pushIntoPaymentOrderDetailsViewCiontonllerWithOrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel]; // 如果行程未开始,进入订单详情
                            strongSelf.isViewDriverStatus = NO; // 可以继续检测出车状态的请求
                        }
                    }
                    else if (ordersDetailsModel.subStatus == OrderStatusCode_DriverReceivedOrder_DetermineStroke) { // 行程确定,进入去接乘客页面
                        
                        [strongSelf pushIntoOrdersDetailsViewControllerWithOrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel]; // 如果行程未开始,进入订单详情
                        strongSelf.isViewDriverStatus = NO; // 可以继续检测出车状态的请求
                    }
                }
            });
            
        }else {
            
            if ([[data allKeys] containsObject:@"data"]) {
                
                if ([data[@"data"] integerValue] == 20001) {
                    
                    IflyMSCManager *iflyMSCManager = [IflyMSCManager startSyntheticSpeechWithText:NetWork_Message];
                    [iflyMSCManager.iFlySpeechSynthesizer setParameter:[NSString stringWithFormat:@"80"] forKey:[IFlySpeechConstant SPEED]];
                }
            }
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_CanReceivingOrder object:nil]; // 发送通知可以继续接单
            strongSelf.isViewDriverStatus = NO; // 可以继续检测出车状态的请求
        }
        
    } failure:^(NSError *error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_CanReceivingOrder object:nil]; // 发送通知可以继续接单
        strongSelf.isViewDriverStatus = NO; // 可以继续检测出车状态的请求
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        });
    }];
}


/**
 进入订单详情,拨打客服电话,投诉
 Code:
 200：［行程确定］司机接单、行程确定 (预约单的状态,即时单没有这个状态)
 600：付款完成、行程结束
 610：乘客完成对车主评价
 900：［新行程］乘客取消
 901:  乘客取消（行程确定后、司机未到达）
 902:  乘客取消（行程确定后、司机到达）
 910: ［新行程］司机取消
 90200：［无费用］［行程确定］乘客取消订单
 90210：［无费用］［去接乘客］乘客取消订单
 90220：［无费用］［等待乘客］乘客取消订单
 91200：［无费用］［行程确定］司机取消订单
 91210：［无费用］［去接乘客］司机取消订单
 91220：［无费用］［等待乘客］司机取消订单
 
 90511：［有费用］［行程确定］乘客取消订单
 90512：［有费用］［去接乘客］乘客取消订单
 90513：［有费用］［等待乘客］乘客取消订单
 91521：［有费用］［行程确定］司机取消订单
 91522：［有费用］［去接乘客］司机取消订单
 91523：［有费用］［等待乘客］司机取消订单
 990：客服关闭订单
 */
- (void)pushIntoOrdersDetailsViewControllerWithOrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    orderDetailsViewController *orderDetailVC = [orderDetailsViewController shareSelf];
    orderDetailVC.title = @"订单详情";
    orderDetailVC.ordersDetailsModel = ordersDetailsModel;
    orderDetailVC.userPassengerModel = userPassengerModel;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.navigationController pushViewController:orderDetailVC animated:YES];
    });
    
}

/**
 进入正在进行的订单页面 , 去接乘客,到达目的地,乘客已上车,前往目的地
 Code:
 210：［去接乘客］司机出发、去接乘客
 220：［等待乘客］司机到达、等待乘客
 300：［行程开始］乘客上车、行程开始
 */
- (void)pushIntoongoingOrdersViewControllerWithOrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {

    ongoingOrdersViewController *vc = [ongoingOrdersViewController shareSelf];
    vc.ordersDetailsModel = ordersDetailsModel;
    vc.userPassengerModel = userPassengerModel;
    
    dispatch_async(dispatch_get_main_queue(), ^{   // 抢到实时单后进入订单详情
        [self.navigationController pushViewController:vc animated:YES];
    });
}

/**
 进入结算页面,确认费用
 Code:
 400：［行程结束］司机送达目的地
 */
- (void)pushIntoendTheTripViewControllerWithOrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    if ([ordersDetailsModel.typeTrip isEqualToString:@"1"]) {
        
        endTheTripViewController *endTheTripVC = [endTheTripViewController shareSelf];
        endTheTripVC.title = @"结算";
        endTheTripVC.userPassengerModel = userPassengerModel;
        endTheTripVC.ordersDetailsModel = ordersDetailsModel;
        [self.navigationController pushViewController:endTheTripVC animated:YES];
    }else if ([ordersDetailsModel.typeTrip integerValue] == 2 || [ordersDetailsModel.typeTrip integerValue] == 4 || [ordersDetailsModel.typeTrip integerValue] == 5 || [ordersDetailsModel.typeTrip integerValue] == 6 || [ordersDetailsModel.typeTrip integerValue] == 7) {
        
        carEndTheTripViewController *vc = [carEndTheTripViewController shareSelf];
        vc.ordersDetailsModel = ordersDetailsModel;
        vc.userPassengerModel = userPassengerModel;
        vc.title = @"结算";
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController pushViewController:vc animated:YES];
        });
    }

}

/**
 待支付页面
 Code:
 500：
 511:
 512:
 513:
 521:
 522:
 523:
 */
- (void)pushIntoPaymentOrderDetailsViewCiontonllerWithOrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    paymentOrderDetailsViewController *paymentOrderDetailVC = [paymentOrderDetailsViewController shareSelf];
    paymentOrderDetailVC.ordersDetailsModel = ordersDetailsModel;
    paymentOrderDetailVC.userPassengerModel = userPassengerModel;
    paymentOrderDetailVC.title = @"订单详情";
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController pushViewController:paymentOrderDetailVC animated:YES];
    });
}




#pragma mark - 获取当前出车考核信息: 出车时间,完成订单,收入流水信息
/// 获取当前出车考核信息: 出车时间,完成订单,收入流水信息
- (void)getCurrentDrivingInfo {
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager getDrivingInfoWithParameters:nil success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
//            [self.willBeginOrderDataSource removeAllObjects];
//            [self.tableView reloadData];
        });
        
        if (NetWork_Success) {
            
            if ([data[@"data"] allKeys].count > 0) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [strongSelf dealHomePageHeaderData:data[@"data"]];
                });
                
            }else {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [strongSelf notGetHomePageDrivingInfo];
                });
                
            }
            
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [strongSelf notGetHomePageDrivingInfo];
            });
            
        }
        
    } failure:^(NSError *error) {
        
    }];
}


/**
 处理首页表头出车考核信息数据源
 */
- (void)dealHomePageHeaderData:(NSDictionary *)data {
    
    // 01月20日
    NSString *dateString = [self getDateStringWithDateFormater:@"MM月dd日" Interval:[data[@"date"] doubleValue]];
    // 星期五
    NSString *weekString = [self getWeekStringWithWeekArray:@[@"星期日" , @"星期一" , @"星期二" , @"星期三" , @"星期四" , @"星期五" , @"星期六" , @"星期日"] Interval:[data[@"date"] doubleValue]];
    // 01:30(小时分钟)
    NSString *timeString = [NSString stringWithFormat:@"已出车%02ld:%02ld" , (NSInteger)[data[@"onWorkTime"] doubleValue] / 1000 / 60 / 60 , (NSInteger)[data[@"onWorkTime"] doubleValue] / 1000 / 60 - 60 * ((NSInteger)[data[@"onWorkTime"] doubleValue] / 1000 / 60 / 60)];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.drivingTimeLabel.text = [NSString stringWithFormat:@"%@,%@,%@" , dateString , weekString , timeString];
        self.completeOrderNumberLabel.text = [NSString stringWithFormat:@"%ld" , [data[@"totalOrderDone"] integerValue]];
        self.incomeLabel.text = [NSString stringWithFormat:@"%.1f" , [data[@"totalIncome"] doubleValue]];
    });
}


/**
 处理将要开始的订单,展示在首页

 @param orderDic 订单列表
 */
- (void)dealWillBeginOrderCellWithOrderListDic:(NSDictionary *)orderDic {
    
    if (orderDic) {

        HomeMessageInformationListOfCenterModel *model = [HomeMessageInformationListOfCenterModel new];
        [model setValuesForKeysWithDictionary:orderDic];
        [self.willBeginOrderDataSource addObject:model];

        
        dispatch_async(dispatch_get_main_queue(), ^{
            
//            [self.tableView reloadSections: withRowAnimation:(UITableViewRowAnimationNone)];
            [self.tableView reloadData];
        });

    }
}

- (void)notGetHomePageDrivingInfo {
    
    self.drivingTimeLabel.text = [NSString stringWithFormat:@"%@,%@" , [self getOneDayDateWithDateFormatter:@"MM月dd日" dayNumber:0] , [self getOneDayWeekWithWeekArray:@[@"星期日" , @"星期一" , @"星期二" , @"星期三" , @"星期四" , @"星期五" , @"星期六" , @"星期日"] dayNumber:0]];
    self.completeOrderNumberLabel.text = [NSString stringWithFormat:@"%d" , 0];
    self.incomeLabel.text = [NSString stringWithFormat:@"%.1f" , 0.0];
}


/**
 获取某一天的日期

 @param dateFormater 输出日期的格式
 @param dayNumber 距离今天的天数
 @return 返回指定格式的日期
 */
- (NSString *)getOneDayDateWithDateFormatter:(NSString *)dateFormater dayNumber:(NSInteger)dayNumber {
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:dayNumber * 24 * 60 * 60];
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:dateFormater];
    NSString *dateStr = [formater stringFromDate:date];
    return dateStr;
}


/**
 返回某一天星期

 @param weekArray 星期的数组例如 @[@"星期日" , @"星期一" , @"星期二" , @"星期三" , @"星期四" , @"星期五" , @"星期六"];
 @param dayNumber 距离今天的天数,如果今天,那么0,如果明天1,如果昨天-1
 @return 返回星期数组中的日期
 */
- (NSString *)getOneDayWeekWithWeekArray:(NSArray *)weekArray dayNumber:(NSInteger)dayNumber {
    
    if (weekArray == nil) {
        
        return @"";
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:dayNumber * 24 * 60 * 60];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:date];
    
    return [NSString stringWithFormat:@"%@" , [weekArray objectAtIndex:theComponents.weekday - 1]];
}


/**
 根据时间戳返回指定格式的日期

 @param dateFomater 指定格式的日期格式
 @param interval 时间戳
 @return 返回的指定格式的时间戳
 */
- (NSString *)getDateStringWithDateFormater:(NSString *)dateFomater Interval:(NSTimeInterval)interval {
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval / 1000.0];
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:dateFomater];
    return [formater stringFromDate:date];
}

- (NSString *)getWeekStringWithWeekArray:(NSArray *)weekArray Interval:(NSTimeInterval)interval {
    
    if (weekArray == nil) {
        
        return @"";
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval / 1000.0];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:date];
    
    return [NSString stringWithFormat:@"%@" , [weekArray objectAtIndex:theComponents.weekday - 1]];
}

#pragma mark - 预约单提醒接口
- (void)appointOrderWarning {
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager appointOrderWarningWithParameters:nil success:^(id data) {
       
        __strong typeof(self) strongSelf = weakSelf;
        if (NetWork_Success) {
            
            [self.willBeginOrderDataSource removeAllObjects];
            
            if ([[data allKeys] containsObject:@"data"]) {
                
                NSDictionary *dataDic = data[@"data"];
                if ([dataDic isKindOfClass:[NSDictionary class]]) {
                    
                    HomePageAppointOrderWarningModel *model = [HomePageAppointOrderWarningModel new];
                    [model setValuesForKeysWithDictionary:dataDic];
                    [strongSelf.willBeginOrderDataSource addObject:model];
                }
            }
        }else {
            
            [strongSelf.willBeginOrderDataSource removeAllObjects];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
            [strongSelf.tableView reloadData];
        });
        
    } failure:^(NSError *error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
        });
    }];
}

#pragma mark - SendLocationManagerDelegate 代理方法
- (void)refreshAttendanceInfoOfDriver {
    
    [self getCurrentDrivingInfo];
    [self appointOrderWarning];
}

- (void)getWaitingFareWithSendLocationManager:(SendLocationManager *)sendLocationManager {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_GetRealFare object:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
